/*
 * 项目名称:    wms-server-jeecg
 * 创建人员:    FanZhiwen
 * 创建时间:    2023-09-26
 */
package org.jeecg.modules.flow.callback.delivery.in;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.jeecg.weibo.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.modules.business.doc.business.entity.WmsInReceipt;
import org.jeecg.modules.business.doc.business.entity.WmsInReceiptMaterial;
import org.jeecg.modules.business.doc.business.mapper.WmsInReceiptMapper;
import org.jeecg.modules.business.doc.business.service.IWmsInReceiptMaterialService;
import org.jeecg.modules.business.doc.business.service.IWmsInReceiptService;
import org.jeecg.modules.business.doc.business.vo.WmsInReceiptPage;
import org.jeecg.modules.business.repertory.entity.vo.RepertoryDocumentVO;
import org.jeecg.modules.business.repertory.entity.vo.RepertoryVO;
import org.jeecg.modules.business.repertory.service.IWmsRepertoryService;
import org.jeecg.modules.business.warehouse.entity.WmsInReceiptTask;
import org.jeecg.modules.business.warehouse.mapper.WmsInReceiptTaskMapper;
import org.jeecg.modules.business.warehouse.service.IWmsInReceiptTaskService;
import org.jeecg.modules.flow.callback.delivery.util.CommonDeliveryTaskUtil;
import org.jeecg.modules.flow.callback.enums.DocumentStatusEnum;
import org.jeecg.modules.flow.callback.inbound.order.InBoundBeanUtils;
import org.jeecg.modules.flow.sys.common.BaseCustomBeanRun;
import org.jeecg.modules.flow.sys.entity.dto.BaseFlowDto;
import org.jeecg.modules.flow.sys.exception.FlowNoActionException;
import org.jeecg.modules.flow.sys.service.WorkFlowService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 入库单提交bean(用于保存-提交-过账)并且通知mes
 *
 * @author FanZhiwen
 * @version 1.0.0
 * @since 2023-09-26
 */
@Component
@Slf4j
public class InBoundReceiptDBRKSubmitBean<T> extends BaseCustomBeanRun<T> {
    private final String WARN = "2";
    private final String STOP = "3";
    @Autowired
    private IWmsInReceiptService wmsInReceiptService;
    @Autowired
    private IWmsRepertoryService wmsRepertoryService;
    @Autowired
    private IWmsInReceiptMaterialService inReceiptMaterialService;
    @Autowired
    private IWmsInReceiptTaskService iWmsInReceiptTaskService;
    @Resource
    private WmsInReceiptMapper wmsInReceiptMapper;
    @Resource
    private WmsInReceiptTaskMapper wmsInReceiptTaskMapper;
    @Autowired
    private InBoundBeanUtils inBoundBeanUtils;

    @Autowired
    private CommonDeliveryTaskUtil commonDeliveryTaskUtil;

    @Autowired
    private WorkFlowService workFlowService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void actureRun() {
        //保存
        BaseFlowDto baseFlowDto = this.getBaseFlowDto();
        // 转class.自定义class,data对应的class
        baseFlowDto.translateClass(WmsInReceiptPage.class);
        WmsInReceiptPage data = (WmsInReceiptPage) baseFlowDto.getData();
        WmsInReceipt wmsInReceipt = new WmsInReceipt();
        BeanUtils.copyProperties(data, wmsInReceipt);
        String id = null;
        //commonDeliveryTaskUtil.checkInReceiptMaterialWarehouseArea(wmsInReceipt.getDocumentType(),data.getWmsInReceiptMaterialList());
        commonDeliveryTaskUtil.checkExistInTransitRepertory(wmsInReceipt.getWmsInReceiptTaskId());
        if (StrUtil.isBlank(data.getId())) {
            id = wmsInReceiptService.saveMain(wmsInReceipt, data.getWmsInReceiptMaterialList());
            baseFlowDto.setInfoId(id);
        } else {
            id = data.getId();
            //提交的时候如果传了物料详情,说明是先编辑再提交的,更新一下
            if (CollectionUtil.isNotEmpty(data.getWmsInReceiptMaterialList())){
                 wmsInReceiptService.updateMain(wmsInReceipt, data.getWmsInReceiptMaterialList());
            }
        }
        //入库单提交校验
        Map<String, List<String>> valid = inBoundBeanUtils.valid(id);
        if (CollectionUtil.isNotEmpty(valid.get(WARN))) {
            if (!data.isJumpSecondCheck()){
                baseFlowDto.setSecondaryBoundingBox(true);
                Result<String> result = new Result<>();
                result.setCode(CommonConstant.SECONDBOX);
                String msg = "";
                List<String> list = valid.get(WARN);
                for (int i = 0; i < list.size(); i++) {
                    msg = msg + (i+1)+". "+list.get(i)+"<br/>";
                }
                result.setResult(msg);
                baseFlowDto.setResult(result);
                //流程不执行,但是上面已保存的数据不会回滚,要么回滚,要么删除多余的数据
                throw new FlowNoActionException("需要回滚上面已保存的数据");
            }else {
                addStock(id);
            }
        } else {
            addStock(id);
        }
        if (CollectionUtil.isNotEmpty(valid.get(STOP))) {
            throw new BusinessException(valid.get(STOP).get(0));
        }
        WmsInReceipt inReceipt = wmsInReceiptMapper.selectById(id);
        if (ObjectUtil.isNotEmpty(inReceipt.getWmsInReceiptTaskId())) {
            WmsInReceiptTask inReceiptTask = wmsInReceiptTaskMapper.selectById(inReceipt.getWmsInReceiptTaskId());
            if ("-1".equals(inReceiptTask.getDocumentStatus())) {
                throw new BusinessException("上游入库任务已关闭,不可入库!");
            }
        }
        //将入库单状态改为已完成
        wmsInReceiptService.update(new LambdaUpdateWrapper<WmsInReceipt>()
                .set(WmsInReceipt::getDocumentStatus, DocumentStatusEnum.COMPLETE.getCode())
                .eq(WmsInReceipt::getId,inReceipt.getId())
        );
        //根据单据id获取任务id
        String taskId=inReceipt.getWmsInReceiptTaskId();
        inBoundBeanUtils.updateTaskWareHouseStatus(taskId);
        //更新任务状态
        iWmsInReceiptTaskService.updateReceipt(id);
        //将任务改为执行中
        iWmsInReceiptTaskService.update(new LambdaUpdateWrapper<WmsInReceiptTask>()
                .set(WmsInReceiptTask::getDocumentStatus,"5")
                .eq(WmsInReceiptTask::getId,inReceipt.getWmsInReceiptTaskId())
        );
        //调用回调
        workFlowService.backAutoCommit(taskId, inReceipt);
        if (data.isJumpSecondCheck()){
            //任务不可分批出入库,并且点了二次确认,将任务修改为完成
            if (CollectionUtil.isNotEmpty(valid.get("printConfigCanBatch"))){
                iWmsInReceiptTaskService.update(new LambdaUpdateWrapper<WmsInReceiptTask>()
                        .set(WmsInReceiptTask::getDocumentStatus, DocumentStatusEnum.COMPLETE.getCode())
                        .eq(WmsInReceiptTask::getId,inReceipt.getWmsInReceiptTaskId())
                );
            }
        }
        //第一个表单产生通知mes任务开始(TASK_STARTED)
//        inBoundBeanUtils.sendMesStart(inReceipt.getWmsInReceiptTaskId());
        baseFlowDto.setResult(Result.OK("操作成功"));
    }

    void addStock(String inReceipt) {
        List<WmsInReceiptMaterial> materialList = inReceiptMaterialService.list(new LambdaQueryWrapper<WmsInReceiptMaterial>()
                .eq(WmsInReceiptMaterial::getWmsInReceiptId, inReceipt)
        );
        RepertoryDocumentVO repertoryDocumentVOS = new RepertoryDocumentVO();
        WmsInReceipt wmsInReceipt = wmsInReceiptMapper.selectById(inReceipt);
        repertoryDocumentVOS.setDocumentType(1);
        repertoryDocumentVOS.setInvoicesId(inReceipt);
        repertoryDocumentVOS.setWmsBasicSupplierId(wmsInReceipt.getWmsBasicSupplierId());
        repertoryDocumentVOS.setStackNumber(wmsInReceipt.getStackNumber());
        List<RepertoryVO> repertoryVOS = new ArrayList<>();
        materialList.forEach(one -> {
            RepertoryVO vo = BeanUtil.toBean(one, RepertoryVO.class);
            vo.setWmsBasicWarehouseId(one.getWmsBasicWarehouseId());
            vo.setWmsBasicWarehouseAreaId(one.getWmsBasicWarehouseAreaId());
            vo.setWmsBasicWarehouseAreaLocationId(one.getWmsBasicWarehouseAreaLocationId());
            vo.setWmsBasicMaterialId(one.getWmsBasicMaterialId());
            vo.setStockQuantity(one.getWarehouseQuantity());
            vo.setBatchCode(one.getBatchCode());
            vo.setStockQuantitySub(one.getAssistQuantity());
            vo.setUnitSub(one.getUnitAssistId());
            vo.setSpecification(one.getSpecification());
            repertoryVOS.add(vo);
        });
        repertoryDocumentVOS.setRepertoryVOS(repertoryVOS);
        //增加库存
        wmsRepertoryService.add(repertoryDocumentVOS);
        String deliveryTaskId = commonDeliveryTaskUtil.getDeliveryTaskIdByInTaskId(wmsInReceipt.getWmsInReceiptTaskId());
        //删除在途库存
        wmsRepertoryService.deleteInTransitRepertory(repertoryDocumentVOS,deliveryTaskId);
    }
}
